package str;

/**
 * @ Author     ：侯耀祖
 * @ Description：
 */
public class reverseWords {
    public String reverseWords(String s) {
        StringBuilder str = removeSpace(s);
        str.reverse();
        reverseWord(str);
        return str.toString();
    }
    public StringBuilder removeSpace(String str){
        int start = 0;
        int end = str.length()-1;
        while (str.charAt(start) == ' ')start++;
        while (str.charAt(end) == ' ')end--;
        StringBuilder sb = new StringBuilder();
        while (start <= end){
            char c = str.charAt(start);
            if (c != ' ' || sb.charAt(sb.length() - 1) != ' ') {
                sb.append(c);
            }
            start++;
        }
        return sb;
    }
    public void reverseString(StringBuilder s, int start, int end) {
        while (start < end){
            char temp = s.charAt(start);
            s.setCharAt(start, s.charAt(end));
            s.setCharAt(end, temp);
            start++;
            end--;
        }
    }
    public void reverseWord(StringBuilder s){
        int start = 0;
        int end = 1;
        int len = s.length();
        while (start < len){
            while (end < len && s.charAt(end) != ' '){
                end++;
            }
            reverseString(s, start, end);
            start++;
        }
    }
}
